package com.yangzc.lion.common.model;

import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.cglib.transform.impl.InterceptFieldCallback;

import com.yangzc.lion.sys.util.IDGenerator;
import com.yangzc.lion.sys.util.ObjectUtil;


/**
 * 域模型的基类，建议大部分的域模型继承，只有域模型继承了该类，后面的Dao、Service、Action等才能继承通用的相应的实现。<br>
 * 使用限制条件：<br>
 * 
 */
public abstract class BaseModel implements IBaseModel {

	private static final long serialVersionUID = -8514084604115405888L;

	private transient InterceptFieldCallback $CGLIB_READ_WRITE_CALLBACK;

	protected String fdId;

	public String getFdId() {
		if (fdId == null) {
			fdId = IDGenerator.generateID();
		}
		return fdId;
	}

	public void setFdId(String fdId) {
		this.fdId = fdId;
	}

	public void recalculateFields() {

	}

	protected Object writeLazyField(String fieldName, Object oldValue,
			Object newValue) {
		if (getInterceptFieldCallback() == null) {
			return newValue;
		}
		return getInterceptFieldCallback().writeObject(this, fieldName,
				oldValue, newValue);
	}

	protected Object readLazyField(String fieldName, Object oldValue) {
		if (getInterceptFieldCallback() == null) {
			return oldValue;
		}
		return getInterceptFieldCallback()
				.readObject(this, fieldName, oldValue);
	}

	public InterceptFieldCallback getInterceptFieldCallback() {
		return $CGLIB_READ_WRITE_CALLBACK;
	}

	public void setInterceptFieldCallback(
			InterceptFieldCallback interceptfieldcallback) {
		$CGLIB_READ_WRITE_CALLBACK = interceptfieldcallback;
	}

	public boolean equals(Object object) {
		if (this == object)
			return true;
		if (object == null)
			return false;
		if (!this.getClass().getName().equals(object.getClass().getName())) {
			return false;
		}
		BaseModel objModel = (BaseModel) object;
		return ObjectUtil.equals(objModel.getFdId(), this.getFdId(), false);
	}

	public int hashCode() {
		HashCodeBuilder rtnVal = new HashCodeBuilder(-426830461, 631494429);
		rtnVal.append(getModelClassName(this));
		rtnVal.append(getFdId());
		return rtnVal.toHashCode();
	}

	public String getModelClassName(Object mainModel) {
		String rtnVal = mainModel.getClass().getName();
		int i = rtnVal.indexOf('$');
		if (i > -1)
			rtnVal = rtnVal.substring(0, i);
		return rtnVal;
	}

}
